{block name="content"}
<form class="layui-form layui-card" action="{:sysuri()}" data-auto="false" method="post" autocomplete="off" lay-filter="stock_form" id="stock_form" onsubmit="return false;">
    <div class="layui-card-body padding-left-40">
        <div class="layui-form-item">
            <table id="sku_stock" lay-filter="sku_stock"></table>
        </div>
        <div class="layui-form-item text-center">
            <div class="layui-input-block">
                <input type="hidden" name="goods_id" value="{$goods_info.id|default=0}">
                <input type="hidden" name="account_id" value="{$goods_info.account_id|default=0}">
                <input type="hidden" name="shop_id" value="{$goods_info.shop_id|default=0}">
                <button class="layui-btn" type='button' lay-submit lay-filter="stock_submit">保存数据</button>
            </div>
        </div>
    </div>
</form>
{/block}

{block name="script"}
<script>
    layui.use(['table','form'],function(){
        let table = layui.table
        let form = layui.form
        let form_data = form.val('stock_form')
        // 渲染，并获得实例对象
        let inst = table.render({
            elem: '#sku_stock', url: '{:sysuri("getOzonWarehouseList")}',method: 'post',even:true,lineStyle: 'height: 150px;',
            id:'sku_stock',where: form_data,toolbar: '#toolbar_stock',
            cols: [[
                {type: 'checkbox', width:60, fixed: 'left'},
                {field:'goods_nu',title:'{:lang("商品SKU")}',minWidth:80,align:'center'},
                {field:'attribute_titles',title:'{:lang("商品规格")}',minWidth:100,align:'center'},
                {field:'stock_info',title:'{:lang("库存")}',minWidth:300,align:'left', templet: '#stock_info_tpl'},
            ]],
            parseData: function(res){ // res 即为原始返回的数据
                return {
                    "code": res.code, // 解析接口状态
                    "msg": res.info, // 解析提示文本
                    "count": res.data.total, // 解析数据长度
                    "data": res.data.item // 解析数据列表
                };
            },
        });
        form.on('submit(stock_submit)', function(data){
            let table_data = table.getData('sku_stock')
            let err_flag = false
            let form_data = form.val('stock_form')
            layui.each(table_data,function(i,item){
                let stock_list = {}
                layui.each(form_data,function(k, k_val){
                    if(k.indexOf(item.goods_nu) > -1){
                        if(isNotEmpty(k_val) && (k_val - 0) >= 0){
                            let parts = k.split('[');
                            let warehouse_ids = parts.slice(2)  // 跳过 前2个 部分
                                .map(part => part.replace(']', '')); // 移除 ]
                            if(isNotEmpty(warehouse_ids)){
                                stock_list[warehouse_ids[0]] = k_val
                            }
                        }
                    }
                })
                if(!isNotEmpty(stock_list)){
                    err_flag = true
                    $.msg.error(item.goods_nu+'{:lang("请至少设置一个仓库库存")}')
                    return true
                }
                item.stock_list = stock_list
            })
            if(err_flag){
                return false
            }
            httpRequest('{:sysuri("setInventory")}', {sku_data:JSON.stringify(table_data),account_id:form_data.account_id,shop_id:form_data.shop_id}, 'post', function(info, data){
                $.msg.success(info, 3, function(){
                    $.msg.closeThisModal('#stock_form')
                })
            })
            return false;
        })

        table.on('toolbar(sku_stock)', function(obj){
            let id = obj.config.id;
            let checkStatus = table.checkStatus(id);
            let othis = lay(this);
            switch(obj.event){
                case 'pullStock':
                    //let ck_data = checkStatus.data;
                    let table_data = table.getData('sku_stock')
                    let sku_ids = [];
                    layui.each(table_data,function(i,item){
                        sku_ids.push(item.id)
                    })
                    if(sku_ids.length <= 0){
                        $.msg.error('请选择要同步库存的SKU')
                        return false
                    }
                    let sku_ids_str = sku_ids.join(',');
                    httpRequest('{:sysuri("pullSingleGoodsStock")}', {sku_ids:sku_ids_str}, 'post', function(info, data){
                        $.msg.success(info, 3, function(){
                            inst.reload()
                        })
                    })
                    break;
            };
            return false
        });
    })
</script>
<script type="text/html" id="stock_info_tpl">
    {{#  layui.each(d.stockData, function(index, item){ }}
        <div class="layui-form-item">
            <div class="layui-input-group">
                <div class="layui-input-prefix">
                    {{= item.warehouse_name }}
                </div>
                <input type="number" value="{{= item.stock}}" lay-affix="number" min='0' max="1000000" name="stock[{{= d.goods_nu }}][{{= item.warehouse_id }}]" gw_id="{{= item.warehouse_id }}" placeholder="请输入库存数量" class="layui-input">
            </div>
        </div>
    {{#  }); }}
</script>

<script type="text/html" id="toolbar_stock">
    <div class="layui-btn-container">
        <!--{if auth("pullSingleGoodsStock")}-->
        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="pullStock">{:lang('同步库存')}</button>
        <!-- {/if} -->
    </div>
</script>
{/block}